package handler

import (
	"GetUserInfo/model"
	pb "GetUserInfo/proto"
	"GetUserInfo/utils"
	"context"
	log "github.com/micro/micro/v3/service/logger"
)

type GetUserInfo struct{}

// Return a new handler
func New() *GetUserInfo {
	return &GetUserInfo{}
}

// Call is a single request handler called via client.Call or the generated client code
func (e *GetUserInfo) MicroGetUser(ctx context.Context, req *pb.Request, rsp *pb.Response) error {
	//根据用户名获取用户信息 在mysql数据库中
	myUser, err := model.GetUserInfo(req.Name)
	if err != nil {
		rsp.Errno = utils.RECODE_USERERR
		rsp.Errmsg = utils.RecodeText(utils.RECODE_USERERR)
		return err
	}
	rsp.Errno = utils.RECODE_OK
	rsp.Errmsg = utils.RecodeText(utils.RECODE_OK)

	//获取一个结构体对象
	var userInfo pb.UserInfo
	userInfo.UserId = int32(myUser.ID)
	userInfo.Name = myUser.Name
	userInfo.Mobile = myUser.Mobile
	userInfo.RealName = myUser.Real_name
	userInfo.IdCard = myUser.Id_card
	userInfo.AvatarUrl = "http://192.168.57.130/" + myUser.Avatar_url

	rsp.Data = &userInfo

	return nil
}

// Stream is a server side stream handler called via client.Stream or the generated client code
func (e *GetUserInfo) Stream(ctx context.Context, req *pb.StreamingRequest, stream pb.GetUserInfo_StreamStream) error {
	log.Infof("Received GetUserInfo.Stream request with count: %d", req.Count)

	for i := 0; i < int(req.Count); i++ {
		log.Infof("Responding: %d", i)
		if err := stream.Send(&pb.StreamingResponse{
			Count: int64(i),
		}); err != nil {
			return err
		}
	}

	return nil
}

// PingPong is a bidirectional stream handler called via client.Stream or the generated client code
func (e *GetUserInfo) PingPong(ctx context.Context, stream pb.GetUserInfo_PingPongStream) error {
	for {
		req, err := stream.Recv()
		if err != nil {
			return err
		}
		log.Infof("Got ping %v", req.Stroke)
		if err := stream.Send(&pb.Pong{Stroke: req.Stroke}); err != nil {
			return err
		}
	}
}
